const fs = require('fs');
const path = require('path');
const { v4 } = require('uuid');

function createUUID() {
    return v4().replace(/-/g, '').toUpperCase();
}

// path.resolve('产品特色.docx');
// path.resolve('123.docx');
// rename(path.resolve('123.docx'), path.resolve('产品特色.docx'));

function rename(oldName, newName) {
    return new Promise((resolve, reject) => {
        const baseName = path.basename(oldName);
        fs.rename(oldName, newName, err => {
            if (err) {
                reject(`${baseName}重命名失败!`);
                return;
            }
            resolve();
        });
    });
}

let arr = [];
const dir = './document';
readDir(dir)
    .then(async files => {
        const length = files.length;
        for (let i = 0; i < length; i++) {
            const absolutePath = path.resolve(dir, files[i]);
            const stat = fs.statSync(absolutePath);
            if (stat.isFile()) {
                await changeFileName(absolutePath);
            }
        }
        console.log(arr);
        // fs.createWriteStream(path.resolve(__dirname, 'backup.js')).write(JSON.stringify(arr, null, 4), 'utf-8');
    });
async function changeFileName(absolutePath) {
    const renameString = createUUIDFileName(absolutePath);
    const renamePath = path.resolve(dir, renameString);
    const fileNameString = getFileName(absolutePath);
    try {
        await rename(absolutePath, renamePath);
    } catch (e) {
        throw e;
    }
    arr.push({
        isShow: true,
        fileName: `/${renameString}`,
        showName: fileNameString
    });
}

function getFileName(pathString) {
    return path.basename(pathString, path.extname(pathString));
}
function createUUIDFileName(absolutePath) {
    const extName = path.extname(absolutePath);
    const uuid = createUUID();
    return `${uuid}${extName}`
}

function readDir(pathString) {
    return new Promise((resolve, reject) => {
        fs.readdir(pathString, (err, files) => {
            if (err) { reject(err) };
            resolve(files);
        });
    });
}